package com.xiaoma.tpo.webservice;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xiaoma.tpo.dao.TimelineDao;
import com.xiaoma.tpo.domain.Timeline;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.domain.UserDevice;
import com.xiaoma.tpo.domain.UserFollow;
import com.xiaoma.tpo.domain.UserFriend;
import com.xiaoma.tpo.domain.UserListening;
import com.xiaoma.tpo.domain.UserListeningRecording;
import com.xiaoma.tpo.dto.FriendDto;
import com.xiaoma.tpo.dto.LoginDto;
import com.xiaoma.tpo.dto.MessagesDto;
import com.xiaoma.tpo.dto.TopListeningVo;
import com.xiaoma.tpo.dto.UserAchievementDto;
import com.xiaoma.tpo.dto.UserAchievementsDto;
import com.xiaoma.tpo.dto.UserBindDto;
import com.xiaoma.tpo.dto.UserDto;
import com.xiaoma.tpo.dto.UserListeningDto;
import com.xiaoma.tpo.dto.UserListeningRecordingDto;
import com.xiaoma.tpo.dto.UserListeningVo;
import com.xiaoma.tpo.resource.TPOConstants;
import com.xiaoma.tpo.resource.TimelineContent;
import com.xiaoma.tpo.service.UserDeviceService;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.service.WordService;
import com.xiaoma.tpo.utils.TPOUtils;

@Controller
@RequestMapping("/service/user")
public class UserWS {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDeviceService userDeviceService;

    @Autowired
    private WordService wordService;

    @Autowired
    private TimelineDao timelineDao;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> register(@RequestBody UserDto userDto) {
        Map<String, Object> result = new HashMap<String, Object>();
        String name = userDto.getName();
        String password = userDto.getPassword();
        String nickname = userDto.getNickname();
        String registerFrom = userDto.getRegisterFrom();
        String msg = userDto.validate();
        if (!StringUtils.isEmpty(msg)) {
            result.put("status", 0);
            result.put("message", msg);
            return result;
        }
        User existUser = userService.findByName(name);
        if (existUser != null) {
            result.put("status", 0);
            result.put("message", "用户名已经存在");
        } else {
            User user = new User();
            user.setName(name);
            user.setPassword(password);
            user.setNickname(nickname);
            user.setRegisterFrom(registerFrom);
            user.setCreatedAt(new Date());
            UUID uuid = UUID.randomUUID();
            user.setToken(uuid.toString());
            try {
                userService.save(user);
                result.put("status", 1);
            } catch (Exception e) {
                result.put("status", 0);
                result.put("message", e);
            }
        }
        return result;

    }

    @RequestMapping(value = "/updateInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateInfo(@RequestHeader String token, @RequestBody UserDto userDto) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        String name = userDto.getName();
        String password = userDto.getPassword();
        String nickname = userDto.getNickname();
        String email = userDto.getEmail();
        String phone = userDto.getPhone();
        String examDate = userDto.getExamDate();
        String avatar = userDto.getAvatar();
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            if (userService.duplicated(user.getId(), name)) {
                result.put("status", 0);
                result.put("message", "用户名已经存在");
            } else {
                // if(file != null && !file.isEmpty()){
                // avatar = UploadImgUtil.uploadImg(file.getBytes(),
                // file.getOriginalFilename());
                // }
                user.setName(name);
                user.setPassword(password);
                user.setNickname(nickname);
                user.setAvatar(avatar);
                user.setEmail(email);
                user.setPhone(phone);
                user.setLastVisit(new Date());
                if (examDate != null && examDate.length() > 0) {
                    user.setExamDate(sf.parse(examDate));
                }
                userService.update(user);
                result.put("status", 1);
                result.put("user", user);
            }

        } catch (Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }

        return result;

    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(@RequestBody LoginDto loginDto) {
        Map<String, Object> result = new HashMap<String, Object>();
        String name = loginDto.getName();
        String password = loginDto.getPassword();
        String device = loginDto.getDevice();
        String loginFrom = loginDto.getLoginFrom();
        String msg = loginDto.validate();
        if (!StringUtils.isEmpty(msg)) {
            result.put("status", 0);
            result.put("message", msg);
            return result;
        }
        try {
            User user = userService.findByNameAndPwd(name, password);
            if (null != user) {
                if (!StringUtils.isEmpty(device)) {
                    UserDevice userDevice = userDeviceService.findByUserIdAndDevice(user.getId(), device);
                    if (userDevice == null) {
                        userDevice = new UserDevice();
                        userDevice.setUserId(user.getId());
                        userDevice.setDevice(device);
                        userDeviceService.save(userDevice);
                    }
                    // 获取匿名用户（手机）的单词进度记录
                    // User anonymous = userService.findByName(device);
                    // if (anonymous != null) {
                    // List<WdUnlockProcess> unlockProcesss =
                    // wordService.findProcessByUserId(anonymous.getId());
                    // for (WdUnlockProcess item : unlockProcesss) {
                    // WdUnlockProcess unlockProcess =
                    // wordService.findProcessByPlanIdAndUserId(item.getWdPlanId(),
                    // user.getId());
                    // if (unlockProcess != null) {
                    // if (item.getWdGroupId() > unlockProcess.getWdGroupId()) {
                    // unlockProcess.setWdGroupId(item.getWdGroupId());
                    // wordService.updateUnlockProcess(unlockProcess);
                    // }
                    // } else {
                    // unlockProcess = new WdUnlockProcess();
                    // unlockProcess.setUserId(user.getId());
                    // unlockProcess.setWdGroupId(item.getWdGroupId());
                    // unlockProcess.setWdPlanId(item.getWdPlanId());
                    // wordService.saveUnlockProcess(unlockProcess);
                    // }
                    // wordService.destroyUnlockProcess(item.getId());
                    // }
                    // }
                }
                user.setLastVisit(new Date());
                user.setLoginFrom(loginFrom);
                user.setLoginCount(user.getLoginCount() + 1);
                userService.update(user);
                result.put("user", user);
            } else {
                result.put("status", 0);
                result.put("message", "用户名或者密码不正确");
            }
        } catch (Exception e) {
            result.put("status", 0);
            result.put("message", e);

        }

        return result;

    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> logout(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();

        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        user.setLastVisit(TPOUtils.getExpiredDate());
        try {
            userService.update(user);
            result.put("status", 1);
        } catch (Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }
        return result;

    }

    @RequestMapping(value = "/listening", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findUserListeningByUserId(@RequestHeader String token, String date) {
        Map<String, Object> result = new HashMap<String, Object>();

        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        UserListening userListening = userService.findUserListeningByUserIdAndDate(user.getId(), date);
        UserListeningVo userListeningVo = null;
        if (userListening != null) {
            Map<String, String> map = userService.getUserListeningRankingAndRateByDate(userListening.getListeningCount(), date);
            userListeningVo = new UserListeningVo();
            userListeningVo.setDate(date);
            userListeningVo.setListeningCount(userListening.getListeningCount());
            userListeningVo.setRanking(map.get("ranking"));
            userListeningVo.setRating(map.get("rating"));
            userListeningVo.setUserId(userListening.getUserId());
            int allTotalCount = userService.getUserTotalListeningCount(user.getId());
            userListeningVo.setTotalCount(allTotalCount);
        }
        result.put("userListening", userListeningVo);
        if (!TPOUtils.isAnonymous(user)) {// 如果不是匿名用户，则更新访问时间
            userService.updateVisitTime(user);
        }
        return result;
    }

    @RequestMapping(value = "/listening", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submitListening(@RequestHeader String token, @RequestBody UserListeningDto userListeningDto) {
        Map<String, Object> result = new HashMap<String, Object>();

        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        Integer count = userListeningDto.getCount();
        String date = userListeningDto.getDate();
        Integer totalCount = userListeningDto.getTotalCount();

        Map<String, String> map = null;
        try {
            UserListening userListening = userService.findUserListeningByUserIdAndDate(user.getId(), date);
            if (userListening == null) {
                userListening = new UserListening();
                userListening.setDate(date);
                userListening.setListeningCount(count);
                userListening.setUserId(user.getId());
                userListening.setTotalCount(totalCount);
                userService.saveUserListening(userListening);
                map = userService.getUserListeningRankingAndRateByDate(count, date);

            } else {
                userListening.setListeningCount(count + userListening.getListeningCount());
                userListening.setTotalCount(totalCount + userListening.getTotalCount());
                userService.updateUserListening(userListening);
                map = userService.getUserListeningRankingAndRateByDate(userListening.getListeningCount(), date);

            }

            UserListeningVo userListeningVo = new UserListeningVo();
            userListeningVo.setDate(date);
            userListeningVo.setListeningCount(userListening.getListeningCount());
            userListeningVo.setRanking(map.get("ranking"));
            userListeningVo.setRating(map.get("rating"));
            userListeningVo.setUserId(userListening.getUserId());
            int allTotalCount = userService.getUserTotalListeningCount(user.getId());
            userListeningVo.setTotalCount(allTotalCount);
            result.put("userListening", userListeningVo);
            if (!TPOUtils.isAnonymous(user)) {// 如果不是匿名用户，则更新访问时间
                userService.updateVisitTime(user);
            }
        } catch (Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }
        return result;
    }

    @RequestMapping(value = "/deviceToken", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getDeviceToken(String imei) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (StringUtils.isEmpty(imei)) {
            result.put("status", 0);
            result.put("message", "invalid IMEI");
            return result;
        }
        try {
            User anonymous = userService.findByName(imei);
            if (anonymous == null) {
                anonymous = new User();
                anonymous.setName(imei);
                anonymous.setCreatedAt(new Date());
                anonymous.setPassword("99999999");
                anonymous.setLastVisit(TPOUtils.getMaxDate());
                UUID uuid = UUID.randomUUID();
                anonymous.setToken(uuid.toString());
                userService.save(anonymous);
            }
            result.put("token", anonymous.getToken());
        } catch (Exception e) {
            result.put("status", 0);
            result.put("message", e);
        }
        return result;

    }

    @RequestMapping(value = "/listening/tops", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> listeningTops(String date) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<TopListeningVo> topLisenings = userService.getListeningTops(date);
        result.put("topLisenings", topLisenings);
        return result;
    }

    @RequestMapping(value = "/achievement/push", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addAchievement(@RequestHeader String token, @RequestBody UserAchievementsDto achievements) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        userService.addAchievement(user, achievements);
        List<UserAchievementDto> rslist = userService.getAchievementList(user.getId());

        result.put("items", rslist);
        return result;
    }

    @RequestMapping(value = "/follow/check", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> checkFollow(@RequestHeader String token, Integer userid) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        UserFollow uf = new UserFollow();
        uf.setFollowUserId(userid);
        uf.setUserId(user.getId());
        boolean flag = userService.checkFollow(uf);
        result.put("rs", flag);
        return result;
    }

    @RequestMapping(value = "/follow/add", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> addFollow(@RequestHeader String token, Integer userid) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        UserFollow uf = new UserFollow();
        uf.setFollowUserId(userid);
        uf.setUserId(user.getId());
        boolean flag = userService.addFollow(uf);
        result.put("rs", flag);
        return result;
    }

    @RequestMapping(value = "/follow/remove", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> removeFollow(@RequestHeader String token, Integer userid) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        UserFollow uf = new UserFollow();
        uf.setFollowUserId(userid);
        uf.setUserId(user.getId());
        boolean flag = userService.removeFollow(uf);
        result.put("rs", flag);
        return result;
    }

    @RequestMapping(value = "/follow/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> removeFollow(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        List<User> list = userService.getMyFollow(user.getId());
        result.put("rs", list);
        return result;
    }

    @RequestMapping(value = "/msg/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getMessagesList(@RequestHeader String token, int page, int status) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        List<MessagesDto> list = userService.getMessageByUser(user.getId(), page, status);
        result.put("items", list);
        return result;
    }

    @RequestMapping(value = "/msg/read", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> updateMsgStatus(@RequestHeader String token, int msgId) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        userService.updateStatus(msgId);
        result.put("status", 1);
        return result;
    }

    @RequestMapping(value = "/push/bind", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> bindUser(@RequestHeader String token, UserBindDto dto) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        userService.bindBdPush(dto);

        result.put("status", 1);
        return result;
    }

    // @RequestMapping(value = "/loginB",method = RequestMethod.POST)
    // public ModelAndView loginBg(@RequestParam(value = "user_name", required =
    // true) String userName,
    // @RequestParam(value = "user_pwd", required = true) String userPwd){
    // ModelAndView modelAndView = new ModelAndView();
    // boolean flag = userService.loginSys(userName,userPwd);
    // if(flag){
    // modelAndView.setViewName("main");
    // }else{
    // modelAndView.setViewName("login");
    // }
    // return modelAndView;
    //
    // }
    @RequestMapping(value = "/loginB", method = RequestMethod.POST)
    public ModelAndView loginBg(@RequestParam(value = "user_name", required = true) String userName, @RequestParam(value = "user_pwd", required = true) String userPwd, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        // boolean flag = userService.loginSys(userName,userPwd);
        boolean flag = userService.loginSysNew(userName, userPwd);
        if (flag) {
            request.getSession().setAttribute("username", userName);
            modelAndView.addObject("username", userName);
            modelAndView.setViewName("main");
        } else {
            modelAndView.setViewName("login");
        }
        return modelAndView;

    }

    @RequestMapping(value = "/friend/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addFriends(@RequestHeader String token, @RequestBody FriendDto dto) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }

        List<String> names = dto.getNames();
        for (String name : names) {
            User friend = userService.findByName(name);
            if (null != friend) {
                UserFriend userFriend = new UserFriend();
                userFriend.setUserId(user.getId());
                userFriend.setFriendId(friend.getId());
                List<UserFriend> friends = userService.findUserFriends(userFriend);
                if (friends.size() == 0) {
                    userService.saveUserFriend(userFriend);
                }
            }
        }
        userService.updateVisitTime(user);
        result.put("status", 1);
        return result;
    }
    
    @RequestMapping(value = "/friend/add/{userId}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addFriends(@RequestHeader String token, @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        User friend = userService.findById(userId);
        if (friend != null) {
            UserFriend userFriend = new UserFriend();
            userFriend.setUserId(user.getId());
            userFriend.setFriendId(friend.getId());
            List<UserFriend> friends = userService.findUserFriends(userFriend);
            if (friends.size() == 0) {
                userService.saveUserFriend(userFriend);
            }
        }
        userService.updateVisitTime(user);
        result.put("status", 1);
        return result;
    }

    @RequestMapping(value = "/friends", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findFriends(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        List<User> myAddUsers = userService.findFriends(user.getId(), 1);// 主动添加的朋友
        List<User> usersAddMe = userService.findFriends(user.getId(), 2);// 主动添加的朋友
        userService.updateVisitTime(user);
        result.put("status", 1);
        result.put("myAddUsers", myAddUsers);
        result.put("usersAddMe", usersAddMe);
        return result;
    }

    @RequestMapping(value = "/listeningRecording", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveListeningRecording(@RequestHeader String token, @RequestBody UserListeningRecordingDto[] dtos) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        

        for (UserListeningRecordingDto dto : dtos) {
            UserListeningRecording userListeningRecording = userService.findUserListeningRecording(user.getId(), dto.getType(), dto.getDate());
            if (userListeningRecording == null) {
                userListeningRecording = new UserListeningRecording();
                userListeningRecording.setCount(dto.getCount());
                userListeningRecording.setDate(dto.getDate());
                userListeningRecording.setType(dto.getType());
                userListeningRecording.setUserId(user.getId());
                userListeningRecording.setCreatedAt(new Date());
                userService.saveUserListeningRecording(userListeningRecording);
            } else {
                userListeningRecording.setCount(dto.getCount() + userListeningRecording.getCount());
                userService.updateUserListeningRecording(userListeningRecording);
            }
            
            if (dto.getType() == TPOConstants.USER_LISTENING) {// 记录听音timeline
                saveTimeline(user.getId(), TimelineContent.listening(dto.getCount()));
            } else if (dto.getType() == TPOConstants.USER_RECORDING) {// 记录录音timeline
                saveTimeline(user.getId(), TimelineContent.recording(dto.getCount()));
            }
        }

        result.put("listeningRecording", userService.get7DaysRecords(user.getId()));
        result.put("listeningTotal", userService.getUserListeningRecordingTotalCount(user.getId(), TPOConstants.USER_LISTENING));
        result.put("recordingTotal", userService.getUserListeningRecordingTotalCount(user.getId(), TPOConstants.USER_RECORDING));
        userService.updateVisitTime(user);
        return result;
    }

    @RequestMapping(value = "/listeningRecording", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findListeningRecording(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        result.put("listeningRecording", userService.get7DaysRecords(user.getId()));
        result.put("listeningTotal", userService.getUserListeningRecordingTotalCount(user.getId(), TPOConstants.USER_LISTENING));
        result.put("recordingTotal", userService.getUserListeningRecordingTotalCount(user.getId(), TPOConstants.USER_RECORDING));

        userService.updateVisitTime(user);
        return result;
    }

    @RequestMapping(value = "/timeline", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getTimeline(@RequestHeader String token) {
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if (null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;

        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {// 大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        Timeline entity = new Timeline();
        entity.setUserId(user.getId());
        List<Timeline> timelines = timelineDao.findByColumns(entity);
        result.put("timelines", timelines);
        userService.updateVisitTime(user);
        return result;
    }

    private void saveTimeline(int userId, String content) {
        Timeline tl = new Timeline();
        tl.setContent(content);
        tl.setUserId(userId);
        tl.setCreatedAt(new Date());
        timelineDao.insert(tl);
    }

    public static void main(String args[]) {
    }

}
